package com.cloud.animationtestdemo.strage

import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.view.View

/**
 * @author: njb
 * @date:   2025/1/1 23:35
 * @desc:   描述
 */
class TranslateAnimationStrategy :BaseAnimationStrategy{
    private val translationXProperty = PropertyValuesHolder.ofFloat("translationX", 0f)
    private val translationYProperty = PropertyValuesHolder.ofFloat("translationY", 0f)

    override fun getAlphaForProgress(progress: Float): Float {
        // 这里的透明度计算可以根据位移进度来简单关联，比如进度越大越不透明
        return 1 - progress
    }

    fun animateView(view: View, startX: Float, startY: Float, endX: Float, endY: Float, duration: Long) {
        translationXProperty.setFloatValues(startX, endX)
        translationYProperty.setFloatValues(startY, endY)

        val animator = ValueAnimator.ofPropertyValuesHolder(translationXProperty, translationYProperty)
        animator.duration = duration
        animator.addUpdateListener { animation ->
            val currentX = (animation as? ValueAnimator)?.getAnimatedValue(startX.toString()) as? Float?: endX
            val currentY = (animation as? ValueAnimator)?.getAnimatedValue(startY.toString()) as? Float?: endY
            view.translationX = currentX
            view.translationY = currentY
            val progress = animation.animatedFraction
            val alpha = getAlphaForProgress(progress)
            view.alpha = alpha
        }
        animator.start()
    }
}